Amazon SQS is a fully managed message queuing service that allows you to decouple the components of a cloud application by enabling communication between them asynchronously. It provides a reliable, scalable, and cost-effective way to transmit any volume of data at any level of throughput without losing messages or requiring other services to be available.
import boto3
import time
# Initialize the SQS client
sqs_client = boto3.client('sqs', region_name='your-region') # Replace 'your-region' with your AWS region
# Create a new SQS queue
queue_name = 'MyQueue'
response = sqs_client.create_queue(QueueName=queue_name)
queue_url = response['QueueUrl']
# Send a message to the queue
message_body = 'Hello, SQS!'
response = sqs_client.send_message(QueueUrl=queue_url, MessageBody=message_body)
print(f"Message sent: {response['MessageId']}")
# Receive and process messages from the queue
while True:
messages = sqs_client.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=1, VisibilityTimeout=30)
if 'Messages' in messages:
for message in messages['Messages']:
print(f"Received message: {message['Body']}")
# Process the message (in this example, just printing the message body)
time.sleep(2) # Simulate processing time
# Delete the processed message from the queue
sqs_client.delete_message(QueueUrl=queue_url, ReceiptHandle=message['ReceiptHandle'])
else:
print("No messages in the queue. Waiting...")
time.sleep(5)
This Python example demonstrates basic usage of Amazon SQS:
Make sure to replace 'your-region' with your AWS region before running the script. Also, be aware that this example runs in an infinite loop, checking for messages every 5 seconds.
To run this script, you'll need to have the `boto3` library installed. You can install it using the following command:
pip install boto3